<template>
  <div class="All">
    <div class="card-container">
      <el-card shadow="never"
        class = "el-card-1"
      >
    <el-button type="primary" plain @click="calculation" class="AllButton">
      <el-icon><DataAnalysis /></el-icon>计算水环境容量
    </el-button>
    <el-button type="primary" plain @click="Updatatable" class="AllButton">
      <el-icon><Refresh /></el-icon>更新表格
    </el-button>

      </el-card>
    </div>

    <el-card style="border: 1px solid #ddd; margin-top: 0;">
      <el-table
          class = "d-inline-grid"
          :data="RiverTable"
          stripe
          style="width: 100%; font-size: 12px;"
          row-key="id"
          :has-n-o="false"
          :row-style="{ height: '5px' }"
          height="500"
          @row-dblclick="dbclick"
          @sort-change="handleSortChange"
          ref="multipleTableRef"
          border
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column
            v-for="item in filteredRiverTable"
            :label="item.label"
            :prop="item.prop"
            min-width="180"
        ></el-table-column>
<!--        拿到所有河道属性表表单-->
        <el-table-column
            v-for="item in parameterMap"
            :prop="item.prop"
            :label="item.label"
            min-width="180"
            editable sortable="custom">
          <template v-slot="scope">
            <el-input
                v-if="scope.row.index + ',' + scope.column.index == currentCell"
                :ref="scope.row.index + ',' + scope.column.index"
                v-model="scope.row[item.prop]"
                @blur="hideInput(scope.row)"
                @change="alterTableData(scope.row.id,
                                        scope.row.period,
                                        scope.row.backgroundcod,
                                        scope.row.backgroundtp,
                                        scope.row.backgroundnh3,
                                        scope.row.designhead,
                                        scope.row.designflow,
                                        scope.row.qualityobjective,
                                        )"
                style="border-radius: 4px; border: 1px solid #377f9e;"
            />
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

</template>

<!-- ------------------------------------------------------------------------------- -->
<script setup lang="ts">
import { ref,reactive,watch } from 'vue'
import { Search, Refresh, Download, DataAnalysis } from '@element-plus/icons-vue';
import axios from 'axios';
import {ElCard, ElMessage, ElTable} from 'element-plus'
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-quartz.css";
import { AgGridVue } from "ag-grid-vue3";
import "ag-grid-charts-enterprise";
// 通过getCurrentInstance 获取
import { getCurrentInstance, onMounted,computed } from 'vue'
const { baseURL } = getCurrentInstance().appContext.config.globalProperties
onMounted(() => {
  console.log(baseURL) // baseURL
})

const {proxy} = getCurrentInstance()
console.log(proxy.$baseUrl)


import { Get, Post,Put } from "@/axios/api";
const url=ref('/plantInfo/list')
const loginForm = ref({
  username: 'admin',
  password: '123456',
})
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10
})
const modelSatus = reactive({
  status: false,
});
const form = reactive({
  input: "",
  list: {},
});
interface User {
  date: string
  name: string
  address: string
}

const parameterMap = [
  { label: '设计水位(m)', prop: 'designhead' },
  { label: '换水周期(d)', prop: 'period' },
  { label: '设计流量(m³/d)', prop: 'designflow' },
  { label: 'COD背景浓度(mg/L)', prop: 'backgroundcod' },
  { label: 'NH₃-N背景浓度(mg/L)', prop: 'backgroundnh3' },
  { label: 'TP背景浓度(mg/L)', prop: 'backgroundtp' },
];




// const rowData = ref([])
const showrows=ref([])
const showtotal = ref(0);
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const toggleSelection = (rows?: User[]) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}

const loading = ref(true)
const props2 = defineProps<{ msg: string ,selData:{} }>()
/*var selList = [];//定义一个空数组
if(props2.selData.hasOwnProperty("OBJECTID")){
  selList.push(props2.selData);
  showrows.value=selList;
  console.log("push:"+showrows.value);
}*/
const childSelMethod = (childSelData: {}) => {
  console.log('childSelData method called:'+childSelData);
  var selList = [];//定义一个空数组
  if(childSelData.hasOwnProperty("OBJECTID")){
    selList.push(childSelData);
    showrows.value=selList;
    showtotal.value = 1;
    console.log("push:"+showrows.value);
  } else {
    console.log("push:"+"no OBJECTID");
  }
};
const childMethod = (str: string) => {
  console.log('Child method called：'+str);
};
defineExpose({
  childMethod,childSelMethod
});
watch(props2.selData, (newData) => {
  console.log(`new newData is: ${newData}`)
})

const currentPage4 = ref(1)
const pageSize4 = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
currentPage4.value=Math.floor(showrows.value/pageSize4.value);

const handleSizeChange = (val: number) => {
  pageSize4.value=val;
  console.log(`${val} items per page`)
  //GetAll();
  MutiSearch();
}
const handleCurrentChange = (val: number) => {
  currentPage4.value=val;
  console.log(`current page: ${val}`)
  // GetAll();
  MutiSearch();
}



const gridApi = ref();
const rowSelection = ref(null);
const paginationPageSize = ref(null);
const paginationPageSizeSelector = ref(null);

rowSelection.value = "multiple";
// paginationPageSize.value = 10;
// paginationPageSizeSelector.value = [10, 25, 50,10000];
const onGridReady = (params) => {
  gridApi.value = params.api;
};
const gridDiv = document.querySelector("#myGrid");


function onBtWhich(){
  var cellDefs = gridApi.value.getEditingCells();
  if (cellDefs.length > 0) {
    var cellDef = cellDefs[0];
    console.log(
        "editing cell is: row = " +
        cellDef.rowIndex +
        ", col = " +
        cellDef.column.getId() +
        ", floating = " +
        cellDef.rowPinned,
    );

    cellDefs.forEach(cellDef => {
      console.log(cellDef.rowIndex);
      console.log(cellDef.column.getId());
      console.log(cellDef.floating);
    });

  } else {
    console.log("no cells are editing");
  }
};

const stopEditing = (params) => {
  console.log("stopEditing");
}
const startEditingCell = (params) => {
  console.log("startEditingCell");
}
const cellEditingStopped=(event) => {
  console.log("cellEditingStopped");
}

// function onCellValueChanged(event) {
//   console.log(`New Cell Value: ${event.value}`);
//   console.log(`New Cell Value: ${event.rowIndex}-${showrows.value[event.rowIndex].codstandard}`);
//   console.log(`New Cell Value: ${event.column.colId}`);
//   alterTableData(showrows.value[event.rowIndex].objectid,showrows.value[event.rowIndex].codstandard,showrows.value[event.rowIndex].nh3standard,showrows.value[event.rowIndex].tpstandard,showrows.value[event.rowIndex].inflowcoefficient) ;
// }

import {onBeforeMount} from "vue";
const autoGroupColumnDef = ref(null);
const sideBar = ref(null);
onBeforeMount(() => {
  autoGroupColumnDef.value = {
    minWidth: 250,
  };
  sideBar.value = "columns";
});

let username = ref('')
let email = ref('')

// function GetAll() {
//   Get('/River/RiverTable',{  pageNum: currentPage4.value,pageSize: pageSize4.value}).then((response) => {
//     const { code, msg, rows,total,data: res } = response.data;
//     if (code === 200) {
//       showrows.value=rows;
//       showtotal.value = total;
//       console.log(showrows.value);
//       //console.log(total);
//       ElMessage.success(msg ?? "Submitted!");
//     } else {
//       ElMessage.error(msg);
//     }
//   });
// }
// GetAll();
const RiverTable = ref([]);

function updateMethod(){
  GetAllwithoutPagehelper();
}
function GetAllwithoutPagehelper() {
  //Pollution/GetAll
  //plantInfo/list
  // axios接口
  // http://1.1.1.200:9602/Pollution/GetAllwithoutPagehelper
  // /Pollution/GetAll
  Get("/River/RiverTable",{}).then((response) => {
    const { code, msg, data: res } = response.data;
    if (code === 200) {
      RiverTable.value=res;
      //showrows.value=data;
      // showtotal.value = total;
      // console.log(total);

      ElMessage.success(msg ?? "Submitted!");
    } else {
      ElMessage.error(msg);
    }
  });
}
GetAllwithoutPagehelper();



/*const query = () => {
  GetAll();
}*/
// const query2 = () => {
//   //console.log('2222:')
//   console.log(username.value)
// }


function calculation(){



  Post('/River/calculate',{}).then((response) => {
    const { code, msg, data,rows,total: res } = response.data;
    if (code === 200) {
      console.log("计算后重新获取数据");
      ElMessage.success(msg ?? "Submitted!");
    } else {
      ElMessage.error(msg);
    }
  });
}

const Updatatable=() => {
  updateMethod();
}

//原参数id改为objectid
function alterTableData(id,
                        period,
                        backgroundcod,
                        backgroundtp,
                        backgroundnh3,
                        designhead,
                        designflow,
                        qualityobjective) {
  if(id!=""){
    Put('/River/alterTableData',{
      "id":id,
      "period":period,
      "backgroundcod":backgroundcod,
      "backgroundtp":backgroundtp,
      "backgroundnh3":backgroundnh3,
      "designhead":designhead,
      "designflow":designflow,
      "qualityobjective":qualityobjective}).then((response) => {
      const { code, msg, data,rows,total: res } = response.data;
      if (code === 200) {
        ElMessage.success(msg ?? "Submitted!");
      } else {
        ElMessage.error(msg);
      }
    });
  }
}


const currentCell = ref(null)
// 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
function tableCellClassName({ row, column, rowIndex, columnIndex }) {
  row.index = rowIndex
  column.index = columnIndex
  //console.log(rowIndex, columnIndex)
}
// 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell
// 拼接后类似这样："1,0","1,1",
function dbclick(row, column) {
  console.log(row, column)
  currentCell.value = row.index + ',' + column.index
  console.log(currentCell)
  // input 自动获取焦点
  if (column.property === 'processid_name' || column.property === 'processmoudel_name') {
    // 双击后自动获得焦点
    this.$nextTick(() => {
      this.$refs[row.index + ',' + column.index].focus()
    })
  }
}
// 关闭编辑状态
function hideInput(row) {
  this.currentCell = null
}

function sortChange(){
  console.log('sortChange');
}

function downloadFile(fileUrl) {
  const link = document.createElement('a');
  link.href = fileUrl;
  //link.setAttribute('download', fileName);
  link.click();
}

const handleSortChange = ({ column, prop, order }) => {
  showrows.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else if (order === 'descending') {
      return a[prop] < b[prop] ? 1 : -1;
    }
    return 0;
  });
};


/*const typeSelect = document.getElementById('typeSelect');
console.log("typeSelect:"+typeSelect);
*/
const typeSelect = ref(null);
onMounted(() => {
  console.log(typeSelect.value); // 在组件挂载后也可以访问
  //注册监听事件，接收传参
  // proxy.mittBus.on('visitDataTimeLine', (data) => {
  //   console.log("visitDataTimeLine B:"+data);
  //   GetAllwithoutPagehelper();
  // });
});
console.log("end typeSelect:"+typeSelect);
typeSelect.onchange = function () {
  console.log(typeSelect.value+":onchange:"+this.value);
  //map.removeInteraction(draw);
  //addInteraction();
};
function typeSelectChange() {
  console.log(typeSelect.value+":onchange:");
}

const selValue = ref('')
//   const selOptions = [
//   {
//     value: 'Option1',
//     label: 'Option1',
//   },
//   {
//     value: 'Option2',
//     label: 'Option2',
//   },
//   {
//     value: 'Option3',
//     label: 'Option3',
//   },
//   {
//     value: 'Option4',
//     label: 'Option4',
//   },
//   {
//     value: 'Option5',
//     label: 'Option5',
//   },
// ]

const showColumnNames = ref([]);
// const filteredRiverTable = showColumnNames.value.filter((item) => {
//   // return !parameterMap.some((param) => param.prop === item.prop);
// });
// const filteredRiverTable = showColumnNames.value.filter(item => !parameterMap.includes(item));
// const filteredRiverTable = showColumnNames.value.filter(item => !parameterMap.value.includes(item));
const filteredRiverTable = ref([]);
function getColumnName() {
  // axios接口
  Get('/River/getcolumnname',{}).then((response) => {
    const { code, msg, data: res } = response.data;
    if (code === 200) {
      showColumnNames.value=res;
      // filteredRiverTable.value = showColumnNames.value.filter(item=>item.prop=='riverid');
      // 去除重复
      filteredRiverTable.value = showColumnNames.value.filter((item) => {
        return !parameterMap.some((param) => param.prop === item.prop);
      })
      console.log(showColumnNames.value);
    } else {
      ElMessage.error(msg);
    }
  });
}
getColumnName() ;

// 过滤 showColumnNames 中不需要的 prop

const searchValue=ref('');
function MutiSearch(){
  const seljson= {pageNum: currentPage4.value,pageSize: pageSize4.value,[selValue.value]:searchValue.value.trim()};
  console.log("MutiSearch:"+seljson);
  const seljson2= {pageNum: currentPage4.value,pageSize: pageSize4.value,selName:selValue.value,selValue:searchValue.value.trim()};
  console.log("MutiSearch:"+seljson);
  Get('/Pollution/MutiSearch',seljson).then((response) => {
    const { code, msg, rows,total,data: res } = response.data;
    if (code === 200) {
      console.log("条件查询");
      showrows.value=rows;
      //showrows.value=data;
      showtotal.value = total;
      console.log(showrows.value);
      ElMessage.success(msg ?? "Submitted!");
      // GetAll();

      /*localStorage.setItem("token", res.token);
      ElMessage.success(msg ?? "Submitted!");
      router.push({
        path: "/", // HelloWorld.vue在路由配置文件中定义的路径
        params: {
          isLogged: true,
        },
      });*/
    } else {
      ElMessage.error(msg);
    }
  });
}
function query(){
  currentPage4.value=1;
  MutiSearch();
}

function downloadFileCsv(){
  console.log("exportExcel");
  Post('/exportExcel',{}).then((response) => {
    const { code, msg, data,rows,total: res } = response.data;
    if (code === 200) {
      console.log("下载csv");
      ElMessage.success(msg ?? "Submitted!");
    } else {
      ElMessage.error(msg);
    }
  });
}
</script>


<style scoped>
.custom-table-row-height .el-table__row {
  height: 20px; /* 自定义行高 */
}



/* 调整单元格内部垂直居中 */
.custom-table-row-height .el-table__row .cell {
  height: 30px;
  line-height: 30px;
}


.card-container {
  width: 100%;
  margin: 20px auto;
  height: auto ; /* 高度自动调整 */
  margin-bottom: 5px;
}

.el-card{
  --el-card-padding: 5px;}

.el-card-1 {
  /* 卡片整体样式 */

  border-radius: 10px; /* 增加圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 轻微阴影效果 */
  padding: 5px; /* 内边距 */
  display: flex;
  height: min-content;
  justify-content: space-around; /* 水平居中且两边按钮 */
  flex-direction: column; /* 如果希望按钮竖直排列，则取消注释这行并注释掉上一行 */
}

.example-showcase .el-loading-mask {
  z-index: 9;
}

.AllButton{
  font-size: 12px;
  padding: 10px;
  border-radius: 5px; /* 按钮圆角 */
  height: min-content;
}

.AllButton:hover {
  background-color: rgba(0, 0, 0, 0.05); /* 示例：轻微的背景色变化 */
  cursor: pointer; /* 显示指针为手型 */
}


.el-table th, .el-table td {
  font-size: 5px; /* 替换为您希望的字体大小 */
}


el-table.cell {
  font-size: 12px !important;
}
span{
  font-size: 12px;
}
.el-select__selection{
  font-size: 12px;
}
.All{
  font-size: 12px;
}
</style>